﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;

namespace XoLib.CatchException
{
    /*
    /// <summary>
    /// simplifies the designation
    /// <example> CLogOnFile.WriteMessage("KeyDown").Write(); </example>/// 
    /// </summary>
  //  public partial class CLogOnSmtp : CLogger<CLogSmtp> { }
    */

    /// <summary>
    /// simplifies the designation
    /// <example> CLogOnFile.WriteMessage("KeyDown").Write(); </example>/// 
    /// </summary>
    public class SmtpInfo
    {
        /// <summary>
        /// Server Smtp
        /// </summary>
        public string server;

        /// <summary>
        /// From Address
        /// </summary>
        public string from;

        /// <summary>
        /// To Address
        /// </summary>
        /// <example> Info.to.Add("Test@test.fg"); </example>/// 
        public List<string> to = new List<string>();

        /// <summary>
        /// Subject of the message
        /// </summary>        
        public string subject;

        /// <summary>
        /// NetworkCredential
        /// </summary>
        /// <example> Info.Credential = new System.Net.NetworkCredential("test@MyTest.fr", "01234");; </example>/// 
        public System.Net.NetworkCredential Credential;
    }

    /// <summary>
    /// Write error and message in a MessageBox
    /// </summary>
    /// <example> CLogger CLogMessage .WriteMessage("Sample").Write(); </example>/// 
    public class CLogSmtp : IActionLog
    {
        /// <summary>
        /// Connection Info
        /// </summary>        
        private static SmtpInfo _Info = null;

        /// <summary>
        /// Set StmpInfo; 
        /// </summary>   
        public static SmtpInfo Info
        {
            set
            {
                _Info = value;
            }
        }

        /// <summary>
        /// <para>
        /// <param name="Entry">LogEntry</param>
        /// </para>
        /// Call by the .Write(); 
        /// </summary>
        public void Write(LogEntry Entry)
        {
            if (_Info == null)
                return;

            MailMessage message = new MailMessage();
            message.From = new MailAddress(_Info.from);
            foreach (string s in _Info.to)
                message.To.Add(s);
            message.Subject = _Info.subject;
            message.Body = Entry.Doc.OuterXml;

            SmtpClient client = new SmtpClient(_Info.server, 25);
            client.Credentials = _Info.Credential;
            try
            {
                client.Send(message);
            }
            catch(Exception ex)
            {
                XoLib.CatchException.CLogManager.WriteException(ex).Write();
            }
#if NET45
            client.Dispose();
#endif
        }
    }
}
